<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\Pinyin;
use App\Models\PostCatlog;
use App\Models\PostItem;

class PostCatlogController extends BaseController
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function index(){

        if ($this->isOnSubmit()) {
            $catloglist = $this->request->input('catloglist');
            if ($catloglist) {
                $pinyin = new Pinyin();
                foreach ($catloglist as $catid=>$catlog) {
                    if ($catlog['name']) {
                        if (!$catlog['identifier']) {
                            $catlog['identifier'] = $pinyin->getPinyin($catlog['name']);
                        }
                        $catlog['enable'] = intval($catlog['enable']);
                        $catlog['displayorder'] = intval($catlog['displayorder']);
                        PostCatlog::where('catid', $catid)->update($catlog);
                    }
                }
                PostCatlog::updateCache();
            }
            return $this->messager()->message(trans('sysmessage.info save success'))->render();
        }else {

            return $this->view('admin.postcatlog.catlog',[
                'catloglist'=>$this->getCatlogs()
            ]);
        }
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function newCatlog(){

        $catid = $this->request->input('catid');
        if ($this->isOnSubmit()){
            $catlog = $this->request->post('catlog');
            $pinyin = new Pinyin();
            $catlog['identifier'] = $pinyin->getPinyin($catlog['name']);
            if ($catid) {
                PostCatlog::where('catid', $catid)->update($catlog);
            }else {
                PostCatlog::insert($catlog);
            }
            PostCatlog::updateCache();
            return $this->messager()->message(trans('sysmessage.info save success'))->render();
        }else {
            $this->assign([
                'catid'=>$catid,
                'catlog'=>[
                    'name'=>'',
                    'fid'=>0,
                    'available'=>1,
                    'template_index'=>'',
                    'template_list'=>'',
                    'template_detail'=>'',
                    'keywords'=>'',
                    'description'=>''
                ],
                'catloglist'=>$this->getCatlogs()
            ]);

            if ($catid) {
                $catlog = PostCatlog::find($catid);
                if ($catlog) $this->assign(['catlog'=>$catlog]);
            }

            return $this->view('admin.postcatlog.newcatlog');
        }
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \Exception
     */
    public function delete(){
        $catid = $this->request->input('catid');
        if ($this->isOnSubmit()) {
            $moveto = intval($this->request->get('moveto'));
            $deleteChilds = intval($this->request->get('deleteChilds'));

            if (!$deleteChilds && !$moveto){
                return $this->messager()->error()->message(trans('sysmessage.invalid parameter'))->render();
            }

            if ($deleteChilds) {
                $catIds = PostCatlog::fetchAllChildIds($catid);
                PostItem::whereIn('catid', $catIds)->get()->map(function (PostItem $item){
                    $item->delete();
                });
                PostCatlog::whereIn('catid', $catIds)->delete();
            }else {
                PostCatlog::where('fid', $catid)->update(['fid'=>$moveto]);
                PostItem::where('catid', $catid)->update(['catid'=>$moveto]);
                PostCatlog::where('catid', $catid)->delete();
            }

            PostCatlog::updateCache();
            return $this->messager()->message(trans('sysmessage.info delete success'))
                ->links([
                    [trans('sysmessage.back_list'), admin_url('postcatlog')]
                ])->render();
        }else {

            $this->assign([
                'catid'=>$catid,
                'catlog'=>PostCatlog::find($catid),
                'catloglist'=>$this->getCatlogs()
            ]);

            return $this->view('admin.postcatlog.delete');
        }
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \Exception
     */
    public function merge(){
        if ($this->isOnSubmit()) {
            $target = $this->request->post('target');
            $source = $this->request->post('source');
            if ($source && $target && $source != $target) {
                foreach ($source as $catid) {
                    PostItem::where('catid', $catid)->update(['catid'=>$target]);
                    PostCatlog::where('catid', $catid)->delete();
                }
                PostCatlog::updateCache();
            }

            return $this->messager()->message(trans('sysmessage.info update success'))
                ->links([
                    [trans('sysmessage.back_list'), admin_url('postcatlog')]
                ])->render();
        }else {

            return $this->view('admin.postcatlog.merge',[
                'catlogOptions'=>PostCatlog::getOptions()
            ]);
        }
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function setIcon(){
        $catid = $this->request->post('catid');
        $icon  = $this->request->post('icon');
        if ($catid && $icon){
            PostCatlog::where('catid', $catid)->update(['icon'=>$icon]);
            PostCatlog::updateCache();
        }
        return ajaxReturn();
    }

    /**
     * @return array|mixed
     */
    private function getCatlogs()
    {
        $catloglist = [];
        PostCatlog::with('childs')->orderBy('displayorder')->get()->map(function ($catlog) use (&$catloglist){
            $catloglist[$catlog->fid][$catlog->catid] = $catlog;
        });

        if ($catloglist) {
            return $catloglist[0];
        } else {
            return [];
        }
    }
}
